package org.jeecg.modules.carRegister.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.carInformation.entity.CarInformation;
import org.jeecg.modules.carInformation.service.ICarInformationService;
import org.jeecg.modules.carPersonnel.entity.CarPersonnel;
import org.jeecg.modules.carPersonnel.service.ICarPersonnelService;
import org.jeecg.modules.carRegister.entity.CarRegister;
import org.jeecg.modules.carRegister.service.ICarRegisterService;
import org.jeecg.modules.carRegister.util.OCR;
import org.jeecg.modules.carRegister.util.QueryEnv;
import org.jeecg.modules.interfaceMapping.entity.InterfaceMapping;
import org.jeecg.modules.interfaceMapping.service.IInterfaceMappingService;
import org.jeecg.modules.personnelInformation.entity.PersonnelInformation;
import org.jeecg.modules.personnelInformation.service.IPersonnelInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 车辆登记
 * @Author: jeecg-boot
 * @Date: 2024-07-25
 * @Version: V1.0
 */
@Api(tags = "车辆登记")
@RestController
@RequestMapping("/carRegister/carRegister")
@Slf4j
public class CarRegisterController extends JeecgController<CarRegister, ICarRegisterService> {
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;

    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private IPersonnelInformationService personnelInformationService;
    @Autowired
    private ICarInformationService carInformationService;
    @Autowired
    private ICarPersonnelService carPersonnelService;
    @Autowired
    private IInterfaceMappingService interfaceMappingService;
    @Autowired
    QueryEnv queryEnv;
    @Autowired
    OCR ocr;

    private static final String APPID = "wx49ad1b4481e6b941";
    private static final String SECRET = "1dc20043560e708a2b6991a40c32a160";

    // 特定的时间点
    String specificTimeStr = "2024-10-23 20:00:00[Asia/Shanghai]";

    /**
     * 分页列表查询
     *
     * @param carRegister carRegister
     * @param pageNo      pageNo
     * @param pageSize    pageSize
     * @param req         req
     * @return Result
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "主系统-审批通过")
    @ApiOperation(value = "主系统-审批通过", notes = "主系统-审批通过")
    @PostMapping(value = "/pass")
    public Result<?> pass(@RequestBody CarRegister carRegister) {
        String plateNo = carRegister.getPlateNo();
        CarInformation byPlate = carInformationService.getByPlate(plateNo);
        byPlate.setEvnType(carRegister.getEvnType());
        carInformationService.updateById(byPlate);
        carRegister.setRegisterStatus(1);
        carRegisterService.updateById(carRegister);
        return Result.OK("审批成功！");
    }

    /**
     * 添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRegister carRegister) {
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 外部-添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-外部-添加")
    @ApiOperation(value = "车辆登记-外部-添加", notes = "车辆登记-外部-添加")
    @PostMapping(value = "/m/addCarRegister")
    public Result<?> addCarRegister(@RequestBody CarRegister carRegister) {
        String plateNo = carRegister.getPlateNo();
        LambdaQueryWrapper<CarRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CarRegister::getPlateNo, plateNo);
        wrapper.last("limit 1");
        CarRegister one = carRegisterService.getOne(wrapper);
        if (one == null) {
            carRegisterService.save(carRegister);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-编辑")
    @ApiOperation(value = "车辆登记-编辑", notes = "车辆登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRegister carRegister) {
        carRegisterService.updateById(carRegister);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id删除")
    @ApiOperation(value = "车辆登记-通过id删除", notes = "车辆登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRegisterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return Result
     */
    @AutoLog(value = "车辆登记-批量删除")
    @ApiOperation(value = "车辆登记-批量删除", notes = "车辆登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRegisterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    /**
     * 导出excel
     *
     * @param request     request
     * @param carRegister carRegister
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRegister carRegister) {
        return super.exportXls(request, carRegister, CarRegister.class, "车辆登记");
    }

    /**
     * 通过excel导入数据
     *
     * @param request  request
     * @param response response
     * @return Result
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRegister.class);
    }

    /**
     * 司机第一次登记
     *
     * @param jsonObject jsonObject
     * @return Result
     */
    @AutoLog(value = "外部-司机登记")
    @ApiOperation(value = "外部-司机登记", notes = "外部-司机登记")
    @PostMapping("/m/register")
    public Result<?> register(@RequestBody JSONObject jsonObject) {
        String openId = jsonObject.getString("openId");
        PersonnelInformation byOpenId = personnelInformationService.getByOpenId(openId);
        if (byOpenId == null) {
            PersonnelInformation personnelInformation = jsonObject.toJavaObject(PersonnelInformation.class);
            personnelInformationService.save(personnelInformation);
        } else {
            String phoneNum = jsonObject.getString("phoneNum");
            String driverName = jsonObject.getString("driverName");
            String idCard = jsonObject.getString("idCard");
            String driversLicense = jsonObject.getString("driversLicense");
            if (!(Objects.equals(phoneNum, byOpenId.getPhoneNum())
                    && Objects.equals(driverName, byOpenId.getDriverName())
                    && Objects.equals(idCard, byOpenId.getIdCard())
                    && Objects.equals(driversLicense, byOpenId.getDriversLicense()))){
                byOpenId.setPhoneNum(phoneNum);
                byOpenId.setDriverName(driverName);
                byOpenId.setIdCard(idCard);
                byOpenId.setDriversLicense(driversLicense);
                personnelInformationService.updateById(byOpenId);
            }
        }
        String plateNo = jsonObject.getString("plateNo");
        CarInformation byPlate = carInformationService.getByPlate(plateNo);
        if (byPlate == null) {
            String needQuery = jsonObject.getString("needQuery");
            if (!"0".equals(needQuery)) {//需要查：1或null 不需要查：0
                String env = getEnv(jsonObject);
                jsonObject.put("evnType", env);
            }
            CarInformation carInformation = jsonObject.toJavaObject(CarInformation.class);
            carInformation.setLastTime(new Date());
            carInformationService.save(carInformation);
        } else {
            Date producedTime = jsonObject.getDate("producedTime");
            String engineType = jsonObject.getString("engineType");
            String engineManufacturer = jsonObject.getString("engineManufacturer");
            String logisticsCompany = jsonObject.getString("logisticsCompany");
            if (!Objects.equals(producedTime, byPlate.getProducedTime())
                    || !Objects.equals(engineType, byPlate.getEngineType())
                    || !Objects.equals(engineManufacturer, byPlate.getEngineManufacturer())
                    || !Objects.equals(logisticsCompany, byPlate.getLogisticsCompany())){
                if (producedTime != null) byPlate.setProducedTime(producedTime);
                if (!StringUtils.isEmpty(engineType)) byPlate.setEngineType(engineType);
                if (!StringUtils.isEmpty(engineManufacturer)) byPlate.setEngineManufacturer(engineManufacturer);
                if (!StringUtils.isEmpty(logisticsCompany)) byPlate.setLogisticsCompany(logisticsCompany);
            }
            byPlate.setLastTime(new Date());
            carInformationService.updateById(byPlate);
        }
        CarPersonnel carPersonnel = carPersonnelService.getByOpenIdAndPlateNo(openId, plateNo);
        if (carPersonnel == null) {
            CarPersonnel carPersonnel1 = new CarPersonnel();
            carPersonnel1.setOpenId(openId).setPlateNo(plateNo).setLastTime(new Date());
            carPersonnelService.save(carPersonnel1);
        } else {
            carPersonnel.setLastTime(new Date());
            carPersonnelService.updateById(carPersonnel);
        }
        String type = jsonObject.getString("evnType");
        String message;
        if ("5".equals(type) || "6".equals(type) || "D".equals(type)) {
            jsonObject.put("registerStatus", 1);
            message = "审核已通过,允许入场";
        } else {
            jsonObject.put("registerStatus", 0);
            message = "未查询到排放, 请等待人工审核!";
        }

//        // 构建支持时区标识的格式器
//        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
//                .appendPattern("yyyy-MM-dd HH:mm:ss")
//                .optionalStart()
//                .appendLiteral('[')
//                .parseCaseInsensitive()
//                .appendZoneId()
//                .appendLiteral(']')
//                .toFormatter();
//        ZonedDateTime specificTime = ZonedDateTime.parse(specificTimeStr, formatter);
//        // 获取当前时间（北京时间）
//        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
//        String goods = jsonObject.getString("goods");
//        // 比较当前时间和特定时间点
//        if (now.isAfter(specificTime)) {
//            if (!("6".equals(type) || "D".equals(type)) && (("包装油瓶坯".equals(goods) || "小包装油（5L、10L）".equals(goods)))){
//                return Result.OK("已于2024年10月23日20时启动重污染天气橙色预警,国五及以下车辆禁止入场", null);
//            }
//        }

        InterfaceMapping interfaceMapping = interfaceMappingService.getUrlByLocation(jsonObject.getString("location"));
        if (interfaceMapping == null) {
            return Result.error("无法访问到对应的报道位置,请联系管理员");
        }
        String url = interfaceMapping.getBaseUrl()+"/carRegister/carRegister/m/addCarRegister";
        JSONObject post = RestUtil.post(url, jsonObject);
        Integer code = post.getInteger("code");
        return Result.OK(message, post);
    }

    /**
     * 根据openid获取司机信息
     *
     * @param openId 微信openid
     * @return Result
     */
    @AutoLog(value = "外部-根据openid获取司机信息")
    @ApiOperation(value = "外部-根据openid获取司机信息", notes = "外部-根据openid获取司机信息")
    @GetMapping("/m/getUserByOpenId")
    public Result<?> getUserByOpenId(@RequestParam(name = "openId") String openId) {
        PersonnelInformation byOpenId = personnelInformationService.getByOpenId(openId);
        return Result.OK(byOpenId);
    }

    /**
     * 获取货物列表
     *
     * @param location 报道位置
     * @param leadingEnterprise 是否引领型企业
     * @param transportStatus 提货送货
     * @return Result
     */
    @AutoLog(value = "外部-获取货物列表")
    @ApiOperation(value = "外部-获取货物列表", notes = "外部-获取货物列表")
    @GetMapping("/m/getGoods")
    public Result<?> getGoods(@RequestParam(name = "location") String location,
                              @RequestParam(name="leadingEnterprise") String leadingEnterprise,
                              @RequestParam(name = "transportStatus") String transportStatus) {
        InterfaceMapping interfaceMapping = interfaceMappingService.getUrlByLocation(location);
        if (interfaceMapping == null) {
            return Result.error("无法访问到对应的报道位置,请联系管理员");
        }
        String url = interfaceMapping.getBaseUrl() +
                "/basicGoods/basicGoods/m/getGoods?leadingEnterprise=" + leadingEnterprise +
                "&transportStatus=" + transportStatus;
        JSONObject jsonObject = RestUtil.get(url);
        return Result.OK(jsonObject);
    }

    /**
     * 根据报道位置获取字段是否展示
     *
     * @param location 报道位置
     * @return Result
     */
    @GetMapping("/m/getFieldDisplay")
    public Result<?> getFieldDisplay(@RequestParam(name = "location") String location){
        InterfaceMapping interfaceMapping = interfaceMappingService.getUrlByLocation(location);
        if (interfaceMapping == null) {
            return Result.error("无法访问到对应的报道位置,请联系管理员");
        }
        String url = interfaceMapping.getBaseUrl() +
                "/fieldDisplay/fieldDisplay/m/list";
        JSONObject jsonObject = RestUtil.get(url);
        return Result.OK(jsonObject.getJSONObject("result"));
    }

    /**
     * 根据openid获取车辆信息
     *
     * @param openId 微信openid
     * @return Result
     */
    @AutoLog(value = "外部-根据openid获取车辆信息")
    @ApiOperation(value = "外部-根据openid获取车辆信息", notes = "外部-根据openid获取车辆信息")
    @GetMapping("/m/getCarByOpenId")
    public Result<?> getCarByOpenId(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "200") Integer pageSize,
                                    @RequestParam(name = "plateNo", required = false) String plateNo,
                                    @RequestParam(name = "openId") String openId) {
        List<String> list = carPersonnelService.getPlateNoByOpenId(openId ,plateNo);
        if (list == null || list.isEmpty()){
            return Result.error("当前人员无绑定车辆");
        }
        IPage<CarInformation> page = carInformationService.pageByPlateNo(list, pageNo, pageSize);
        return Result.OK(page);
    }

    private String getEnv(JSONObject jsonObject) {
        //新能源车辆，直接通过
        String plateColor = jsonObject.getString("plateColor");
        String plateNo = jsonObject.getString("plateNo");
        if ("4".equals(plateColor) || "6".equals(plateColor)) {
            if (plateNo.length() != 8) {
                throw new RuntimeException("车牌号位数错误");
            }
            return "D";
        }
        String local = queryEnv.getLocal(plateNo);
        if (local != null) {
            return local;
        }
        String location = jsonObject.getString("location");
        String zhongjiao = queryEnv.getZhongJiao(plateNo, plateColor, location);
        if (zhongjiao != null) {
            return zhongjiao;
        }
        String vin = jsonObject.getString("vin");
        String angmei = queryEnv.getAngMei(vin, plateNo, plateColor, location);
        if (angmei != null) {
            return angmei;
        }
        return "X";
    }


    /**
     * 文件上传统一方法
     *
     * @param request 请求
     * @return Result
     */
    @PostMapping(value = "/m/upload")
    public Result<?> upload(HttpServletRequest request) {
        Result<JSONObject> result = new Result<>();
        String savePath = "";
        String bizPath = DateUtil.formatDate(new Date());
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        MultipartFile multipartFile = saveFileWithoutWaterMark(file);
        String plateNo = request.getParameter("plateNo");
        String vin = request.getParameter("vin");
        String name = request.getParameter("name");
        if ("1".equals(name)) {
            try {
                JSONObject jsonObject = ocr.getVin(multipartFile);
                if (!(jsonObject.getString("plate").equals(plateNo) && jsonObject.getString("vin").equals(vin))) {
                    return Result.error("识别图片失败,请保证图片清晰质量");
                } else {
                    result.setResult(jsonObject);
                }
            } catch (Exception e) {
                return Result.error("错误");
            }
        } else if ("99".equals(name)) {
            try {
                JSONObject jsonObject = ocr.getVin(multipartFile);
                result.setResult(jsonObject);
            } catch (Exception e) {
                return Result.error("错误");
            }
        }
//        savePath = this.uploadLocal(file, bizPath);
        savePath = CommonUtils.upload(multipartFile, bizPath, uploadType);
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    public MultipartFile saveFileWithoutWaterMark(MultipartFile file) {
        try {
            if ((1024 * 1024 * 0.1) <= file.getSize()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //小于 1M 的
                if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
                    Thumbnails.of(file.getInputStream()).scale(0.8f).outputQuality(0.5f).toOutputStream(outputStream);
                }
                // 1 - 2M 的
                else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
                    Thumbnails.of(file.getInputStream()).scale(0.7f).outputQuality(0.4f).toOutputStream(outputStream);
                }// 2M 以上的
                else if ((1024 * 1024 * 2) < file.getSize()) {
                    Thumbnails.of(file.getInputStream()).scale(0.5f).outputQuality(0.2f).toOutputStream(outputStream);
                }

                byte[] bytes = outputStream.toByteArray();
                InputStream inputStream = new ByteArrayInputStream(bytes);
                //Boolean b=ImageIO.write(ImageIO.read(inputStream),"jpg",new File("D:/111.jpg"));
                // 转换城新的 MultipartFile 对象
                MultipartFile fileInfos = new MockMultipartFile(Objects.requireNonNull(file.getOriginalFilename()), file.getOriginalFilename(), file.getContentType(), inputStream);
                log.info("源文件大小:{}压缩后的大小:{}", file.getSize(), fileInfos.getSize());
                return fileInfos;
            }
            return file;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @AutoLog(value = "注册表-获取openid")
    @ApiOperation(value="注册表-获取openid", notes="注册表-获取openid")
    @GetMapping(value = "/m/getOpenid")
    public Result<?> getOpenid(@RequestParam(name="code",required=true) String code) {
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ APPID +"&secret="+SECRET+"&code="+code+"&grant_type=authorization_code";
        String s = doGet(url);
        JSONObject jsonObject=JSONObject.parseObject(s);
        if(jsonObject.containsKey("openid")){
            return Result.OK(jsonObject.getString("openid"));
        }
        return Result.error("失败");
    }

    private String  doGet(String url) {
        try {
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = reader.readLine()) != null) {
                    response.append(inputLine);
                }
                reader.close();
                return response.toString();
            } else {
                return "";
            }
        } catch (IOException e) {
            log.error("doGet方法出现异常", e);
        }
        return "";
    }

    @AutoLog(value = "补齐数据-补齐数据")
    @ApiOperation(value="补齐数据-补齐数据", notes="补齐数据-补齐数据")
    @GetMapping("/m/addTest")
    public Result<?> addTest(@RequestParam(name = "location") String location) {
        InterfaceMapping urlByLocation = interfaceMappingService.getUrlByLocation(location);
        String baseUrl = urlByLocation.getBaseUrl();
        String url = baseUrl + "/carRegister/carRegister/m/list?createTime_begin=2024-11-07 12:39:44&pageSize=10000";
        JSONObject jsonObject = RestUtil.get(url);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray records = result.getJSONArray("records");
        List<CarInformation> javaList = records.toJavaList(CarInformation.class);
        List<CarInformation> uniqueCars = javaList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                CarInformation::getPlateNo, // key: plateNo
                                car -> car, // value: car itself
                                (existing, replacement) -> existing // 如果key相同，则保留第一个
                        ),
                        map -> new ArrayList<>(map.values()) // 将Map的值转换为List
                ));
        List<CarInformation> toRemove = new ArrayList<>();
        for (CarInformation uniqueCar : uniqueCars) {
            CarInformation byPlate = carInformationService.getByPlate(uniqueCar.getPlateNo());
            if (byPlate != null) {
                toRemove.add(uniqueCar);
            }
        }
        uniqueCars.removeAll(toRemove); // 一次性移除所有标记的元素
        for (CarInformation carInformation : uniqueCars) {
            carInformation.setId(null).setCreateBy(null).setCreateTime(null).setUpdateTime(null).setUpdateBy(null);
        }
        carInformationService.saveBatch(uniqueCars);
        return Result.OK(uniqueCars.size());
    }

}
